package books4africa

class BookRequestException extends RuntimeException{
	String message
	String request
}

class BookRequestService {
	
	boolean transactional= true
	
	def listRequests(){
		def bookRequest = BookRequest.executeQuery("select req from BookRequest req, Books bk, User tch where (req.book = bk and req.user = tch and req.dateFulfilled is null) order by req.dateRequested desc")
		[bookRequestInstanceList: bookRequest, bookRequestInstanceTotal: bookRequest.size()]
		
	}
	
	int addToRequests(Books book, User user, int bookQty, String desc){
		def addRequest = new BookRequest(book: book, user:user, bookQty:bookQty, dateRequested: new Date(), description: desc)
		
		if (!addRequest.save(flush:true)){
			throw new BookRequestException(
				message: "Unable to save request", 
				request: addRequest.errors.each{println it}
			)
		}
		
		return addRequest.id
	}
	
	def showRequest(int id){
		
		def bookRequestInstance = BookRequest.get(id)
		if (!bookRequestInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'BookRequest.label', default: 'BookRequest'), id])
			redirect(action: "list")
			return
		}

		[bookRequestInstance: bookRequestInstance]
	}
	
	def siteIndex (){
		def results = BookRequest.executeQuery("select req from BookRequest req, Books bk, User tch where req.book = bk and req.user = tch and req.dateFulfilled is null order by req.dateRequested desc")
		
		 if(results.size() > 5)
		 {
			 results = results.subList(0, 5)
		 }
		 
		 return results
	}
	
	def lastFive(){
		def results = BookRequest.executeQuery("select req from BookRequest req, Books bk, User tch where req.book = bk and req.user = tch and req.dateFulfilled is null order by req.dateRequested desc")
		
		 if(results.size() > 5)
		 {
			 results = results.subList(0, 5)
		 }
		 
		 return results
	}
	
	def aSearch (params){
		def results = BookRequest.executeQuery("select distinct req from BookRequest req, Books bk, User tch where req.book = bk and req.user = tch and "
			+	"(bk.category = '" + params.category + "' or '" + params.category + "' = 'All') and "
			+	"(bk.minGradeLevel >= '" + params.minLvl + "' or '" + params.minLvl + "' = 'All') and "
			+   "(bk.maxGradeLevel <= '" + params.maxLvl + "' or '" + params.maxLvl + "' = 'All')")  //, [params.category])
		
		return results
	}
}
